package com.lqd.mall.system.service.impl;

import com.lqd.mall.basis.utils.StringUtils;
import com.lqd.mall.interaction.system.SysRoleEntity;
import com.lqd.mall.interaction.system.SysUserEntity;
import com.lqd.mall.jpa.service.impl.BaseServiceImpl;
import com.lqd.mall.system.repository.SysRoleEntityRepository;
import com.lqd.mall.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 零起点
 * @create 2022-02-20 9:23
 */
@Service
public class SysRoleServiceImpl
        extends BaseServiceImpl<SysRoleEntityRepository,SysRoleEntity,Long>
        implements ISysRoleService {

    @Autowired
    SysRoleEntityRepository sysRoleEntityRepository;

    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (SysUserEntity.isAdmin(userId))
        {
            roles.add("admin");
        }
        else
        {
            List<SysRoleEntity> perms = sysRoleEntityRepository.findByDelFlagAndUserId(userId);
            Set<String> permsSet = new HashSet<>();
            for (SysRoleEntity perm : perms)
            {
                if (StringUtils.isNotNull(perm))
                {
                    permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
                }
            }
            roles.addAll(permsSet);
        }
        return roles;
    }

    @Override
    public String checkRoleNameUniqueByUserId(Long userId) {
        List<SysRoleEntity> roleEntities = sysRoleEntityRepository.findByDelFlagAndUserId(userId);
        if (CollectionUtils.isEmpty(roleEntities)){
            return StringUtils.EMPTY;
        }
        return roleEntities.stream().map(SysRoleEntity::getRoleName).collect(Collectors.joining(","));
    }
}
